<template>
  <div class="personal-center">
    <!-- 用户信息卡片 -->
    <div class="user-card">
      <div class="avatar-container" @click="openEditDialog">
        <div class="avatar">
          <img v-if="userInfo.avatar"
               :src="userInfo.avatar + '?t=' + avatarTimestamp"
               alt="头像"
               class="avatar-img">
          <i v-else class="fas fa-user default-avatar-icon"></i>
        </div>
      </div>
      <div class="username">{{ userInfo.nickname }}</div>
      <div class="address">{{ userInfo.building }}号楼&nbsp;{{userInfo.unit}}单元&nbsp;{{userInfo.room}}</div>
      <div class="points">积分：{{ userInfo.points }}</div>
    </div>

    <!-- 功能菜单 -->
    <div class="menu-section">
      <div
          class="menu-item"
          v-for="item in mainMenu"
          :key="item.id"
          @click="handleMenuClick(item)"
      >
        <div class="menu-icon">
          <i :class="item.icon"></i>
        </div>
        <div class="menu-text">{{ item.text }}</div>
        <div class="menu-arrow">
          <i class="fas fa-chevron-right"></i>
        </div>
      </div>
    </div>

    <!-- 底部菜单 -->
    <div class="footer-menu">
      <div
          class="menu-item"
          v-for="item in footerMenu"
          :key="item.id"
          @click="handleMenuClick(item)"
      >
        <div class="menu-icon">
          <i :class="item.icon"></i>
        </div>
        <div class="menu-text">{{ item.text }}</div>
        <div class="menu-arrow">
          <i class="fas fa-chevron-right"></i>
        </div>
      </div>
    </div>
  </div>


  <!-- 个人信息编辑对话框 -->
  <el-dialog
      v-model="data.showEdit"
      title="编辑个人信息"
      width="600px"
      :close-on-click-modal="false"
  >
    <el-form
        :model="data.editForm"
        :rules="formRules"
        ref="editFormRef"
        label-width="100px"
        label-position="left"
    >
      <!-- 头像上传 -->
      <el-form-item label="头像">
        <el-upload
            class="avatar-uploader"
            action=""
            :http-request="uploadURL"
            :before-upload="handleBeforeUpload"
            :limit="1"
            :show-file-list="false"
        >
          <template #trigger>
            <el-button type="primary">选择图片</el-button>
          </template>

          <div class="avatar-preview">
            <!-- 修复：添加v-if条件 -->
            <img v-if="data.editForm.avatar"
                 :src="data.editForm.avatar + '?t=' + previewTimestamp"
                 alt="头像预览"
                 class="preview-img">
            <div v-else class="avatar-placeholder">
              <i class="el-icon-plus avatar-uploader-icon"></i>
              <div>点击上传</div>
            </div>
          </div>

          <div v-if="uploadStatus" class="upload-status">
            <el-progress
                v-if="uploadStatus === 'uploading'"
                :percentage="uploadProgress"
                status="success"
            />
            <el-alert
                v-if="uploadStatus === 'error'"
                title="上传失败"
                type="error"
                :closable="false"
            />
          </div>
        </el-upload>
      </el-form-item>

      <!-- 性别选择 -->
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="data.editForm.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
          <el-radio :label="0">保密</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 生日选择 -->
      <el-form-item label="生日" prop="birthday">
        <el-date-picker
            v-model="data.editForm.birthday"
            type="date"
            placeholder="选择生日"
            value-format="YYYY-MM-DD"
            style="width: 100%"
        />
      </el-form-item>

      <!-- 居住地址 -->
      <el-form-item label="居住地址" required>
        <div class="address-group">
          <el-form-item prop="building" class="address-item">
            <el-input
                v-model="data.editForm.building"
                placeholder="楼栋号"
                clearable
            />
          </el-form-item>
          <span class="address-divider">-</span>
          <el-form-item prop="unit" class="address-item">
            <el-input
                v-model="data.editForm.unit"
                placeholder="单元号"
                clearable
            />
          </el-form-item>
          <span class="address-divider">-</span>
          <el-form-item prop="room" class="address-item">
            <el-input
                v-model="data.editForm.room"
                placeholder="房间号"
                clearable
            />
          </el-form-item>
        </div>
      </el-form-item>

      <!-- 表单操作按钮 -->
      <el-form-item>
        <div class="form-actions">
          <el-button @click="data.showEdit = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import axios from "@/utils/axios.ts";
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { client } from '@/utils/alioss'
import {localSet} from '../utils/index.ts'

const router = useRouter();

// 用户信息数据
let userInfo = reactive({})

// 表单引用
const editFormRef = ref(null)

// 上传状态
const uploadStatus = ref(null) // null, 'uploading', 'success', 'error'
const uploadProgress = ref(0)

// 解决图片缓存问题的时间戳
const avatarTimestamp = ref(Date.now())
const previewTimestamp = ref(Date.now())

const data = reactive({
  showEdit: false,
  editForm: {
    avatar: null,
    oriFileName: null,
    gender: null,
    birthday: null,
    building: null,
    unit: null,
    room: null
  }
})

const init = () => {
  axios.post("/api/users/getUserInfo")
      .then(res => {
        console.log("res:",res.data)
        Object.assign(userInfo, res.data);
        console.log(userInfo)
      })
}

onMounted(() => {
  init();
})

// 打开编辑对话框
const openEditDialog = () => {
  // 填充表单数据
  Object.assign(data.editForm, userInfo)
  data.showEdit = true
}

const handleBeforeUpload = (file) => {
  console.log("文件上传前验证:", file.name);

  // 获取文件扩展名
  const extension = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase();
  const validExtensions = ['jpeg', 'jpg', 'png', 'webp', 'gif'];

  // 验证文件类型
  if (!validExtensions.includes(extension)) {
    ElMessage.warning('只支持 JPG/JPEG/PNG/WEBP/GIF 格式的图片');
    return false;
  }

  // 验证文件大小 (4MB)
  const isLt4M = file.size / 1024 / 1024 < 4;
  if (!isLt4M) {
    ElMessage.warning('图片大小不能超过 4MB');
    return false;
  }

  // 保存原始文件名
  data.editForm.oriFileName = file.name;
  console.log("上传原始文件名：", data.editForm.oriFileName);

  return true;
}

const uploadURL = (fileObj) => {
  console.log("开始上传图片...");

  const file = fileObj.file;
  uploadStatus.value = 'uploading';

  // 移除 Base64 转换逻辑
  // 直接使用文件对象上传
  // 生成安全的文件名
  const timestamp = Date.now();
  const randomString = Math.random().toString(36).substring(2, 8);
  const extension = file.name.substring(file.name.lastIndexOf('.') + 1);
  const fileName = `avatar/${timestamp}_${randomString}.${extension}`;

  // 模拟上传进度
  const progressInterval = setInterval(() => {
    if (uploadProgress.value < 90) {
      uploadProgress.value += 10;
    }
  }, 200);

  // 使用阿里云OSS上传方法
  client().put(fileName, file)
      .then(res => {
        clearInterval(progressInterval);
        uploadProgress.value = 100;

        setTimeout(() => {
          uploadStatus.value = 'success';
          // 只存储 OSS URL，而不是 Base64 数据
          data.editForm.avatar = res.url;

          // 更新预览时间戳，强制刷新预览图片
          previewTimestamp.value = Date.now();

          ElMessage.success('头像上传成功');
        }, 500);
      })
      .catch(error => {
        clearInterval(progressInterval);
        uploadStatus.value = 'error';
        console.error('头像上传失败:', error);
        ElMessage.error('头像上传失败，请重试');
      });
}

// 表单验证规则
const formRules = reactive({
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthday: [
    { required: true, message: '请选择生日', trigger: 'change' }
  ],
  building: [
    { required: true, message: '请输入楼栋号', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '楼栋号必须为正整数', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单元号', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '单元号必须为正整数', trigger: 'blur' }
  ],
  room: [
    { required: true, message: '请输入房间号', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '房间号必须为正整数', trigger: 'blur' }
  ]
})

// 提交表单
const submitForm = () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      console.log('表单验证通过，提交数据:', data.editForm)

      // 调用API更新用户信息
      axios.post('/api/users/updateUserInfo', data.editForm)
          .then(response => {
            console.log('更新成功', response)
            data.showEdit = false

            // 更新用户信息显示
            Object.assign(userInfo, data.editForm)

            // 更新头像时间戳，强制刷新头像
            avatarTimestamp.value = Date.now()

            console.log("更新后的userInfo",userInfo)

            ElMessage.success('个人信息更新成功')

            console.log("usreINfo:",userInfo);
            console.log(response)

            localSet(userInfo.userId,response.data);

          })
          .catch(error => {
            console.error('更新失败', error)
            ElMessage.error('个人信息更新失败')
          })
    } else {
      ElMessage.warning('请填写完整的表单信息')
      return false
    }
  })
}

// 主菜单数据
const mainMenu = reactive([
  { id: 1, text: '我的发布', location:'myItems', icon: 'fas fa-file-alt' },
  { id: 2, text: '我的订单', location:'myOrders', icon: 'fas fa-clipboard-list' },
  { id: 3, text: '我的帖子', location:'myPosts', icon: 'fas fa-comments' },
  { id: 4, text: '我的收藏', location:'myCollections', icon: 'fas fa-star' },
  { id: 5, text: '我的兑换', location:'myProducts', icon: 'fas fa-gift' }
])

// 底部菜单数据
const footerMenu = reactive([
  { id: 6, text: '设置', location: 'settings', icon: 'fas fa-cog' },
  { id: 7, text: '客服中心', location: 'support', icon: 'fas fa-headset' },
  { id: 8, text: '关于邻里', location: 'about', icon: 'fas fa-info-circle' }
])

// 菜单点击处理
const handleMenuClick = (item) => {
  console.log('点击菜单:', item.text)
  if (item.location) {
    router.push(`/${item.location}`)
  } else {
    console.log(`菜单项 ${item.text} 没有配置路由`)
  }
}
</script>

<style scoped>
.personal-center {
  background-color: #e6f7ff;
  min-height: 100vh;
  padding: 20px;
}

.user-card {
  background: linear-gradient(135deg, #87ceeb, #66b3e0);
  border-radius: 16px;
  padding: 25px 20px;
  color: white;
  text-align: center;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.avatar-container {
  margin-bottom: 15px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: white;
  margin: 0 auto;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
}

/* 修复：添加图片缩放样式 */
.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 关键属性：保持比例并填充容器 */
}

.default-avatar-icon {
  font-size: 40px;
  color: #66b3e0;
}

.username {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 5px;
}

.address {
  font-size: 16px;
  margin-bottom: 10px;
  opacity: 0.9;
}

.points {
  font-size: 16px;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 5px 15px;
  border-radius: 20px;
  display: inline-block;
}

.menu-section {
  background-color: white;
  border-radius: 16px;
  padding: 15px 0;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
  cursor: pointer;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item:hover {
  background-color: #f9f9f9;
}

.menu-icon {
  width: 24px;
  height: 24px;
  margin-right: 15px;
  color: #66b3e0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.menu-text {
  font-size: 16px;
  flex: 1;
}

.menu-arrow {
  color: #ccc;
}

.footer-menu {
  background-color: white;
  border-radius: 16px;
  padding: 15px 0;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

/* 头像上传样式 */
.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-preview {
  margin-top: 15px;
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background-color: #f5f7fa;
}

/* 修复：添加图片预览缩放样式 */
.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 关键属性：保持比例并填充容器 */
}

.avatar-placeholder {
  text-align: center;
  color: #8c939d;
}

.avatar-uploader-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.upload-status {
  margin-top: 15px;
  width: 100%;
  max-width: 300px;
}

/* 地址分组样式 */
.address-group {
  display: flex;
  align-items: center;
}

.address-item {
  flex: 1;
  margin-bottom: 0;
}

.address-divider {
  margin: 0 10px;
  color: #999;
}

/* 表单操作按钮 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .avatar, .avatar-preview {
    width: 120px;
    height: 120px;
  }
}
</style>